﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HtmlAgilityPack;
using Newtonsoft.Json.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;

public partial class yzadmin_data_collect_bengou : YuuzleComic.Web.UI.ManagePage
{
    protected string json = "";
    private JObject result = new JObject();

    string baseUrl = "http://www.bengou.com/all/index.html?contentfolder={0}&areafolder={1}&letterfolder={2}&state={3}&order={4}&p={5}";
    string searchUrl = "http://www.bengou.com/Result?searchstr={0}";
    string contentfolder = "";
    string areafolder = "";
    string letterfolder = "";
    string state = "2";
    string order = "update";
    int p = 1;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            switch (Request["a"])
            {
                case "list":
                    this.ProcessList();
                    break;
                case "single":
                    this.ProcessSingle();
                    break;
                case "import":
                    this.ProcessImport();
                    break;
                default:
                    break;
            }
        }
    }

    private void ProcessImport()
    {
        try
        {
            HtmlWeb webClient = this.getWebClient();
            string[] urlArray = Request["zjurl"].Split('\n');
            Array.Reverse(urlArray);//数组倒序
            foreach (string url in urlArray)
            {
                HtmlDocument doc = webClient.Load(url);
                string js = doc.DocumentNode.SelectSingleNode("/html[1]/body[1]/script[2]").InnerText;
                List<string> tpurl = new List<string>();
                foreach (string item in js.Split('\n')[2].Split(new char[]{'[',']'})[1].Split(','))
	            {
                    tpurl.Add(js.Split('\n')[3].Split('\'')[1] + item.Replace("\"",""));
	            }
                YuuzleComic.Model.zj zj = new YuuzleComic.Model.zj();
                zj.cid = Convert.ToInt32(Request["id"]);
                zj.zjmc = doc.GetElementbyId("chapter_title").InnerText;
                zj.time = DateTime.Now;
                zj.isdownload = false;
                zj.tpadd = Request["tpadd"] + zj.zjmc + "/";
                zj.tps = tpurl.Count;
                zj.tpurl = string.Join("|", tpurl.ToArray());
                YuuzleComic.BLL.zj zjbll = new YuuzleComic.BLL.zj();
                if (urlArray.Length == 1 && !string.IsNullOrEmpty(Request["zjid"]))
                {
                    zj.id = int.Parse(Request["zjid"]);
                    zjbll.Update(zj);
                }
                else
                {
                    zjbll.Add(zj);
                }
            }
            result.Add("success", true);
        }
        catch (Exception e)
        {
            result.Add("success", false);
            result.Add("errorMessage", e.Message);
        }
        finally
        {
            json = result.ToString();
        }
    }

    private string getUrl() {
        return string.Format(baseUrl, new object[] { contentfolder, areafolder, letterfolder, state, order, p });
    }

    private void ProcessSingle()
    {
        try
        {
            HtmlWeb webClient = this.getWebClient();
            HtmlDocument doc = webClient.Load(Request["url"]);
            HtmlNode node = doc.DocumentNode.SelectSingleNode("//*[@class=\"cartoon-intro\"]");
            result.Add("mhmc",node.SelectSingleNode("img[1]").Attributes["alt"].Value);
            result.Add("mhfm", node.SelectSingleNode("img[1]").Attributes["src"].Value);
            result.Add("zzmc", node.SelectSingleNode("div[1]/p[1]/span[1]").NextSibling.InnerText);
            result.Add("zt", node.SelectSingleNode("div[1]/p[2]/span[1]").NextSibling.InnerText);
            result.Add("classname", node.SelectSingleNode("div[1]/p[3]/span[1]").NextSibling.InnerText);
            result.Add("diqu", node.SelectSingleNode("div[1]/p[4]/span[1]").NextSibling.InnerText);
            result.Add("time", node.SelectSingleNode("div[1]/p[5]/span[1]").NextSibling.InnerText);
            if (node.SelectNodes("div[1]/p").Count > 7)
            {
                result.Add("nexttime", node.SelectSingleNode("div[1]/p[6]/span[1]").NextSibling.InnerText);
            }
            result.Add("mhjj", node.SelectSingleNode("div[1]/p[@class='line'][1]/span[1]").NextSibling.InnerText.Trim());
            result.Add("mhjs", node.SelectSingleNode("div[1]/p[@class='line'][2]/span[1]").NextSibling.InnerText);
            JArray chapters = new JArray();
            string[] typeArr = new string[] { "all", "mark" };
            foreach (string type in typeArr)
            {
                HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//*[starts-with(@class, 'section-list " + type + "')]/span/a");
                if (nodes != null)
                {
                    foreach (HtmlNode item in nodes)
                    {
                        JObject chapter = new JObject();
                        chapter.Add("zjmc", item.InnerText);
                        chapter.Add("zjurl", item.Attributes["href"].Value);
                        chapter.Add("type", type == "all" ? "正集" : "番外");
                        chapters.Add(chapter);
                    }
                }
            }
            result.Add("chapters", chapters);
        }
        catch (Exception e)
        {
            result.Add("success", false);
            result.Add("errorMessage", e.Message);
        }
        finally {
            json = result.ToString();
        }
    }

    private void ProcessList()
    {
        try
        {
            contentfolder = Request["contentfolder"];
            areafolder = Request["areafolder"];
            letterfolder = Request["letterfolder"];
            state = Request["state"];
            p = Convert.ToInt32(Request["page"]);
            HtmlWeb webClient = this.getWebClient();
            JArray data = new JArray();
            if (string.IsNullOrEmpty(Request["query"]))
            {
                HtmlDocument doc = webClient.Load(this.getUrl());
                HtmlNodeCollection nodes = doc.GetElementbyId("sa-comic_show_list").SelectNodes("ul/li");
                foreach (HtmlNode node in nodes)
                {
                    JObject jo = new JObject();
                    jo.Add("mhmc", node.SelectSingleNode("p[1]/a[2]").InnerText);
                    jo.Add("mhurl", node.SelectSingleNode("p[1]/a[2]").Attributes["href"].Value);
                    jo.Add("zjmc", node.SelectSingleNode("p[2]/span[1]").InnerText);
                    jo.Add("date", node.SelectSingleNode("p[2]/span[2]").InnerText);
                    jo.Add("zt", node.SelectSingleNode("div[1]/i[1]").InnerHtml);
                    data.Add(jo);
                }
            }
            else
            {
                HtmlDocument doc = webClient.Load(string.Format(searchUrl, new string[] { Request["query"].Trim() }));
                HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//div[@class='search-list']/ul/li");
                foreach (HtmlNode node in nodes)
                {
                    JObject jo = new JObject();
                    jo.Add("mhmc", node.SelectSingleNode("p[1]/a/strong").InnerText);
                    jo.Add("mhurl", node.SelectSingleNode("p[1]/a").Attributes["href"].Value);
                    jo.Add("zjmc", node.SelectSingleNode("p[1]/a/span").InnerText);
                    jo.Add("zzmc", node.SelectSingleNode("p[2]").InnerText.Split('：')[1]);
                    jo.Add("zt", node.SelectSingleNode("p[3]").InnerText.Split('：')[1]);
                    data.Add(jo);
                }
            }
            result.Add("data", data);
            result.Add("total", 20000);
        }
        catch (Exception e)
        {
            result.Add("success", false);
            result.Add("errorMessage", e.Message);
        }
        finally {
            json = result.ToString();
        }

    }

    private HtmlWeb getWebClient()
    {
        HtmlWeb webClient = new HtmlWeb();
        HtmlAgilityPack.HtmlWeb.PreRequestHandler handler = delegate(HttpWebRequest request)
        {
            request.Headers[HttpRequestHeader.AcceptEncoding] = "gzip, deflate";
            request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
            request.CookieContainer = new System.Net.CookieContainer();
            request.Timeout = 500000;
            return true;
        };
        webClient.PreRequest += handler;
        return webClient;
    }
}